<template>
    <view class="container">
        <canvas canvas-id="horizontalBar" id="horizontalBar" class="canvas"></canvas>
    </view>
</template>

<script>
export default {
    data() {
        return {
            progress: 75, // 进度值，范围0-100
        };
    },
    onReady() {
        this.drawProgress();
    },
    methods: {
        drawProgress() {
            const ctx = uni.createCanvasContext('horizontalBar', this);
            const canvasWidth = 300; // canvas宽度
            const canvasHeight = 50; // canvas高度
            const segmentCount = 4; // 分段数
            const segmentWidth = canvasWidth / segmentCount; // 每段宽度

            // 绘制背景
            ctx.fillStyle = '#e8e8e8';
            ctx.fillRect(0, 0, canvasWidth, canvasHeight);

            // 绘制进度
            for (let i = 0; i < segmentCount; i++) {
                const segmentProgress = (this.progress / 100) * segmentCount;
                if (i < segmentProgress) {
                    // 完成的进度段
                    ctx.fillStyle = this.getColor(i);
                    ctx.fillRect(i * segmentWidth, 0, segmentWidth, canvasHeight);
                } else if (i === Math.floor(segmentProgress)) {
                    // 部分完成的进度段
                    ctx.fillStyle = this.getColor(i);
                    ctx.fillRect(i * segmentWidth, 0, segmentWidth * (segmentProgress - i), canvasHeight);
                    break;
                }
            }

            ctx.draw();
        },
        getColor(index) {
            // 根据索引返回不同的颜色
            const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00'];
            return colors[index];
        },
    },
};
</script>

<style>
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.canvas {
    border: 1px solid #000;
}
</style>
